package com.cardbaobao.cardbabyclient.ui.activity.web.js;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.controller.Controller;
import com.cardbaobao.cardbabyclient.callback.ICityInfoCallback;
import com.cardbaobao.cardbabyclient.callback.OnLocationListener;
import com.cardbaobao.cardbabyclient.model.City;
import com.cardbaobao.cardbabyclient.model.MyLocation;
import com.cardbaobao.cardbabyclient.ui.activity.AccountLoginActivity;
import com.cardbaobao.cardbabyclient.ui.activity.ApplyRecordActivity;
import com.cardbaobao.cardbabyclient.ui.activity.CitySelectActivity;
import com.cardbaobao.cardbabyclient.ui.activity.CreditDetailActivity;
import com.cardbaobao.cardbabyclient.ui.activity.LoansDetailActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SpeedCardActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SpeedLoanActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.ChannelWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.share.WebShare;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.LogUtils;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Jiangzx on 2017/8/7 9:13.
 */

public class JsInterface {
    private static final int CODE_LOANS_APPLY_LOGIN = 101;
    //网页需要重新登录
    private static final int CODE_WEB_NEED_RE_LOGIN = 102;
    //申请信用卡时需要登录code
    private static final int CODE_APPLY_CREDIT_CARD_LOGIN=103;
    //申请信用卡时需要选择城市code
    private static final int CODE_APPLY_CREDIT_CARD_CITY=104;
    //贷款红包页面申请贷款需要登录code
    private static final int CODE_LOAN_RED_PACKET_LOGIN=105;
    //网页请求登录
    private static final int CODE_REQUEST_LOGIN=106;
    private Activity mActivity;
    private WebView mWebView;

    private String mCardId;//信用卡id
    private String mCardName;//信用卡名称
    private String mCityId;//城市id，申请信用卡时需要用到
    private String mCityName;//城市名称，申请信用卡时需要用到

    private String mLoanId;//贷款id
    private String mRedPacketId;//红包id
    private String mRedPacketAmount;//红包金额

    //清除webView浏览记录，避免用户回退时一直跳登录页面/某些特定页面
    private boolean needClearHistory;
    private String urlReLoadAfterLogin="";

    WebShare webShare;

    public boolean isNeedClearHistory(){
        return this.needClearHistory;
    }

    /**清除webView浏览记录，同时将needClearHistory设为false[初始状态]*/
    public void clearHistory(){
        mWebView.clearHistory();
        this.needClearHistory=false;
    }

    public JsInterface(@NonNull Activity activity, @NonNull WebView webView){
        this.mActivity=activity;
        this.mWebView=webView;
        LocationUtil.startLocation(mActivity, new OnLocationListener() {
            @Override
            public void locationResult(MyLocation location, int resultCode) {
                if(location!=null){
                    mCityName=location.getCityName();
                    LocationUtil.getProvinceCityIDByCityName(new ICityInfoCallback() {
                        @Override
                        public void onCityInfoResponse(City city) {
                            if(city!=null){
                                mCityId=city.getID();
                            }
                        }
                    },mCityName);
                }
            }
        });
    }

    /**关闭当前页面*/
    @JavascriptInterface
    public void goBack2() {
        destroyActivity();
    }

    /** 登录*/
    @JavascriptInterface
    public void userLogin() {
        Intent intent=new Intent(mActivity, AccountLoginActivity.class);
        intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                Constant.PLY010206);
        mActivity.startActivity(intent);
        overridePendingTransition();
    }

    /**
     * 贷款通道的登录
     * @param quota 填写的贷款额度
     */
    @JavascriptInterface
    public void loansApplyLogin(String quota) {
        Intent intent=new Intent(mActivity,AccountLoginActivity.class);
        intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                Constant.PLY010204);
        mActivity.startActivityForResult(intent, CODE_LOANS_APPLY_LOGIN);
        overridePendingTransition();
    }

    /**
     * 打开信用卡详情页
     *
     * @param cardID       信用卡id
     * @param cardName     信用卡名称
     * @param seriesCardId 同系列卡Id
     */
    @JavascriptInterface
    public void creditDetailed(String cardID, String seriesCardId, String cardName) {
        Intent intent=new Intent(mActivity, CreditDetailActivity.class);
        intent.putExtra(CreditDetailActivity.CARD_ID_S, cardID);
        intent.putExtra(CreditDetailActivity.SERIES_CARD_ID_S, seriesCardId);
        intent.putExtra(CreditDetailActivity.CARD_NAME_S, cardName);
        intent.putExtra(CreditDetailActivity.FROM_PAGE_S, "大家喜欢的同类卡-H5");
        mActivity.startActivity(intent);
    }

    /**
     * @param cardId   信用卡id
     * @param cardName 信用卡名称
     */
    @JavascriptInterface
    public void creditApply(String cardId, String cardName) {
        this.mCardId =cardId;
        this.mCardName =cardName;
        if(ApplicationHelper.getApplication().getIsLogin()){
            preApplyCreditCard();
        }else{
            Intent intent=new Intent(mActivity,AccountLoginActivity.class);
            intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    Constant.PLY010203);
            mActivity.startActivityForResult(intent,CODE_APPLY_CREDIT_CARD_LOGIN);
            overridePendingTransition();
        }
    }

    /**卡宝宝申请条款*/
    @JavascriptInterface
    public void applyForClause() {
        Intent intent=new Intent(mActivity, AgreementWebViewActivity.class);
        intent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "卡宝宝申请服务条款");
        intent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.REGISTRATION_AGREEMENT);
        mActivity.startActivity(intent);
    }

    /**
     * 打开贷款详情页
     * @param loansId   贷款Id
     * @param loansName 贷款名称
     */
    @JavascriptInterface
    public void productDetails(String loansId, String loansName) {
        Intent intent=new Intent(mActivity, LoansDetailActivity.class);
        intent.putExtra(LoansDetailActivity.LOANS_ID_S, loansId);
        intent.putExtra(LoansDetailActivity.LOANS_NAME_S, loansName);
        intent.putExtra(LoansDetailActivity.CAN_ONLY_VIEW_B, true);
        intent.putExtra(LoansDetailActivity.FROM_PAGE_S, "推荐借款组合-H5");
        mActivity.startActivity(intent);
    }

    /**
     * 广告页跳信用卡详情，不关闭当前页面
     *
     * @param id 信用卡id
     * @param name 信用卡名称
     */
    @JavascriptInterface
    public void openDesAndroid(String id, String name, String seriesCard) {
        Intent intent=new Intent(mActivity,CreditDetailActivity.class);
        intent.putExtra(CreditDetailActivity.CARD_ID_S, id);
        intent.putExtra(CreditDetailActivity.SERIES_CARD_ID_S, seriesCard);
        intent.putExtra(CreditDetailActivity.CARD_NAME_S, name);
        intent.putExtra(CreditDetailActivity.FROM_PAGE_S, "热门活动");
        mActivity.startActivity(intent);
    }

    @JavascriptInterface
    /**
     * 广告页打开贷款详情页面，不关闭当前页面
     * @param id 贷款id
     * @param name 贷款名
     */
    public void openLoanDesAndroid(String id, String name) {
        Intent intent=new Intent(mActivity,LoansDetailActivity.class);
        intent.putExtra(LoansDetailActivity.LOANS_ID_S, id);
        intent.putExtra(LoansDetailActivity.LOANS_NAME_S, name);
        intent.putExtra(LoansDetailActivity.CAN_ONLY_VIEW_B, true);
        intent.putExtra(LoansDetailActivity.FROM_PAGE_S, "推荐借款组合-H5");
        mActivity.startActivity(intent);
    }

    /**
     * 广告页跳搜索，不关闭当前页面
     * @param keyWord 搜索词
     */
    @JavascriptInterface
    public void linkMoreAndroid(String keyWord) {
        //老版本js调用逻辑，新版本不做处理
    }

    /**申请贷款完成，共关闭当前页面*/
    @JavascriptInterface
    public void loansApplySuccess() {
        destroyActivity();
    }

    /**
     * 设置城市
     * @param cityId   城市Id
     * @param cityName 城市名称
     */
    @JavascriptInterface
    public void setAppCity(String cityId, String cityName) {
        LocationUtil.setCityName(cityName);
        LocationUtil.setCityID(cityId);
    }

    /**
     * h5点击我自己选
     * @param cardKey 搜索词
     */
    @JavascriptInterface
    public void myChoose(String cardKey) {
        //老版本js调用逻辑，新版本不予处理
    }

    /**
     * 贷款申请第三方链接跳转
     * @param url 第三方贷款url
     */
    @JavascriptInterface
    public void LoansApplyLinkJump(String url) {
        Intent intent=new Intent(mActivity,AgreementWebViewActivity.class);
        intent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "贷款申请");
        intent.putExtra(AgreementWebViewActivity.WEB_URL_S, url);
        mActivity.startActivity(intent);
    }

    /**
     * 网页需要重新登录，重新登录成功后，将用户id追加到拿到的url上，在当前页面重新加载
     *
     * @param url 重新登录后需要加载的url
     */
    @JavascriptInterface
    public void webNeedReLogin(String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent=new Intent(mActivity,AccountLoginActivity.class);
            intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    Constant.PLY010206);
            urlReLoadAfterLogin = url;
            mActivity.startActivityForResult(intent, CODE_WEB_NEED_RE_LOGIN);
        }
    }

    @JavascriptInterface
    public void webNeedReLoginActivity(String successLoadUrl){
        if (!TextUtils.isEmpty(successLoadUrl)) {
            Intent intent=new Intent(mActivity,AccountLoginActivity.class);
            intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    Constant.PLY010206);
            urlReLoadAfterLogin = successLoadUrl;
            mActivity.startActivityForResult(intent, CODE_REQUEST_LOGIN);
        }
    }


    /** 查看办卡记录*/
    @JavascriptInterface
    public void SeeCardRecord() {
        Intent intent=new Intent(mActivity, ApplyRecordActivity.class);
        intent.putExtra(ApplyRecordActivity.CURRENT_TAB_I,
                ApplyRecordActivity.TAB_CREDIT_CARD);
        mActivity.startActivity(intent);
    }

    /**查看贷款记录*/
    @JavascriptInterface
    public void SeeLoanRecord() {
        Intent intent=new Intent(mActivity,ApplyRecordActivity.class);
        intent.putExtra(ApplyRecordActivity.CURRENT_TAB_I,
                ApplyRecordActivity.TAB_LOAN);
        mActivity.startActivity(intent);
    }

    /**重新打开一个WebView，通常是查看协议之类的*/
    @JavascriptInterface
    public void viewAgreementOrTips(String title,String url){
        try{
            Intent intent=new Intent(mActivity,AgreementWebViewActivity.class);
            intent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,
                    URLDecoder.decode(title,Constant.ENCODING));
            intent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                    URLUtil.CBB_WEB_URL+"/"+URLDecoder.decode(url,Constant.ENCODING));
            mActivity.startActivity(intent);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    /**H5信用卡申请总通道总行提交*/
    @JavascriptInterface
    public void creditApplyTotalChannelCollSubmit() {
        UmengEventUtils.clickEvent(mActivity,mActivity.getString(R.string.event_0x033));
    }

    /**H5信用卡申请总通道非总行提交*/
    @JavascriptInterface
    public void creditApplyTotalChannelOtherSumbit() {
        UmengEventUtils.clickEvent(mActivity,mActivity.getString(R.string.event_0x034));
    }

    /**H5信用卡申请单通道总行提交*/
    @JavascriptInterface
    public void creditApplySingleChannelCollSubmit() {
        UmengEventUtils.clickEvent(mActivity,mActivity.getString(R.string.event_0x035));
    }

    /**H5信用卡申请单通道非总行提交*/
    @JavascriptInterface
    public void creditApplySingleChannelOherSubmit() {
        UmengEventUtils.clickEvent(mActivity,mActivity.getString(R.string.event_0x036));
    }

    /**H5贷款申请提交*/
    @JavascriptInterface
    public void loansApplySubmit() {
        UmengEventUtils.clickEvent(mActivity,mActivity.getString(R.string.event_0x037));
    }

    /**
     * H5信用卡通道 申请结果
     */
    @JavascriptInterface
    public void cardSuccessAN() {
        GoogleAnalyticsUtil.setScreenName(Google.CREDIT_SUMBIT);
        LogUtils.d(Google.CREDIT_SUMBIT);
    }

    /**
     * H5贷款通道 申请结果
     */
    @JavascriptInterface
    public void APPLoansApplySuccess() {
        GoogleAnalyticsUtil.setScreenName(Google.LOANS_SUMBIT);
        LogUtils.d(Google.LOANS_SUMBIT);
    }

    /**红包页跳贷款详情页*/
    @JavascriptInterface
    public void RedCreditDetails(String loansId,String loansName){
        Intent intent=new Intent(mActivity,LoansDetailActivity.class);
        intent.putExtra(LoansDetailActivity.LOANS_ID_S,loansId);
        intent.putExtra(LoansDetailActivity.LOANS_NAME_S,loansName);
        mActivity.startActivity(intent);
    }

    /**红包页进贷款通道*/
    @JavascriptInterface
    public void RedChannelDetails(String loansId,String loansName,
                                  String redPacketId,String redPacketAmount){
        this.mLoanId=loansId;
        this.mRedPacketId=redPacketId;
        this.mRedPacketAmount=redPacketAmount;
        if(ApplicationHelper.getApplication().getIsLogin()){
            startLoanRedPacket();
        }else{
            Intent intent=new Intent(mActivity, ChannelWebViewActivity.class);
            intent.setClass(mActivity,AccountLoginActivity.class);
            intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    Constant.PLY010205);
            mActivity.startActivityForResult(intent,CODE_LOAN_RED_PACKET_LOGIN);
            overridePendingTransition();
        }
    }

    /**贷款完成后，返回急速贷款页面*/
    @JavascriptInterface
    public void loanReturnLoanList(){
        Intent intent=new Intent(mActivity, SpeedLoanActivity.class);
        intent.putExtra(SpeedLoanActivity.CODE,"");
        intent.putExtra(SpeedLoanActivity.GO_HOME_B,true);
        mActivity.startActivity(intent);
    }

    /**回到急速办卡页面*/
    @JavascriptInterface
    public void returnCardList(){
        Intent intent=new Intent(mActivity, SpeedCardActivity.class);
        intent.putExtra(SpeedCardActivity.BANK_ID_I,-1);
        intent.putExtra(SpeedCardActivity.BANK_NAME_S,"");
        intent.putExtra(SpeedCardActivity.THEME_NAME_S,"");
        intent.putExtra(SpeedCardActivity.THEME_CODE_S,"");
        mActivity.startActivity(intent);
    }


    /**分享到微信好友与微信朋友圈*/
    @JavascriptInterface
    public void share(String url,String title,String content,String imgUrl){
        try{
            LogUtils.d(url+"\n"+title+"\n"+content+"\n"+imgUrl);
            new WebShare(mActivity).
                    share(URLDecoder.decode(url,Constant.ENCODING),
                    URLDecoder.decode(title,Constant.ENCODING),
                    URLDecoder.decode(content,Constant.ENCODING),
                    URLDecoder.decode(imgUrl,Constant.ENCODING)
                    );
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 分享
     * @param tage 微信、朋友圈、微博、QQ
     * @param tit 标题
     * @param des 内容
     * @param pic 图片
     * @param url 网址
     */
    @JavascriptInterface
    public void toAppShare(String tage,String tit,String des,String pic,String url){
        try{
            LogUtils.d(tage+"\n"+tit+"\n"+des+"\n"+pic+"\n"+url);
            webShare=new WebShare(mActivity);
            webShare.share(tage,
                    URLDecoder.decode(tit,Constant.ENCODING),
                    URLDecoder.decode(des,Constant.ENCODING),
                    URLDecoder.decode(pic,Constant.ENCODING),
                    URLDecoder.decode(url,Constant.ENCODING));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //唤起拨号键盘拨打电话
    @JavascriptInterface
    public void webToAppTel(String tel){
        if(!TextUtils.isEmpty(tel)){
            Intent intent=new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+tel));
            mActivity.startActivity(intent);
        }
    }

    private void destroyActivity(){
        mActivity.finish();
    }

    private void preApplyCreditCard(){
        if(TextUtils.isEmpty(mCityId)||TextUtils.isEmpty(mCityName)){
            //城市id或者城市名称为空，需要用户手动选择城市
            ToastUtil.showToast("请选择当前所在城市");
            Intent intent=new Intent(mActivity, CitySelectActivity.class);
            mActivity.startActivityForResult(intent,CODE_APPLY_CREDIT_CARD_CITY);
            overridePendingTransition();
        }else{
            startApplyCreditCard();
        }
    }

    private void startApplyCreditCard(){
        //h5页面内申请信用卡
        Controller controller=new Controller(mActivity);
        controller.detailPageApplyCreditCard(mCardId, mCardName, mCardId,mCityName,"申请信用卡-H5");
        destroyActivity();
    }

    private void startLoanRedPacket(){
        //贷款红包进贷款申请页面
        Intent intent=new Intent(mActivity,ChannelWebViewActivity.class);
        intent.putExtra(ChannelWebViewActivity.WEB_TITLE_S,"申请贷款");
        String url=URLUtil.APPLY_CARD_LOAN+
                "?Site=APP&ProductLoansID="+
                mLoanId+"&MemberID="+
                ApplicationHelper.getApplication().getUser().getID()+
                "&red_packet="+mRedPacketAmount+"&red_packet_id="+mRedPacketId;
        intent.putExtra(ChannelWebViewActivity.WEB_URL_S,url);
        destroyActivity();
    }

    private void overridePendingTransition(){
        mActivity.overridePendingTransition(R.anim.activity_in_bottom, R.anim.activity_out_top);
    }

    public void onActivityPause(){
        if(webShare!=null){
            webShare.dismissDialog();
        }
    }

    //让jsInterface有机会处理activityResult回调
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CODE_LOANS_APPLY_LOGIN:
                    //老版本用到过，现在已经不使用了，打印下log，不做其他处理
                    LogUtils.d("js调用本地登录，登录成功后回调");
                    break;
                case CODE_APPLY_CREDIT_CARD_LOGIN:
                    preApplyCreditCard();
                    break;
                case CODE_APPLY_CREDIT_CARD_CITY:
                    mCityId = data.getStringExtra(CitySelectActivity.RESULT_CITY_ID_KEY);
                    mCityName = data.getStringExtra(CitySelectActivity.RESULT_CITY_NAME_KEY);
                    startApplyCreditCard();
                    break;
                case CODE_WEB_NEED_RE_LOGIN:
                    needClearHistory = true;
                    String loadUrl = URLUtil.CBB_WEB_URL + "/" +
                            urlReLoadAfterLogin +
                            ApplicationHelper.getApplication().getUser().getID();
                    mWebView.loadUrl(loadUrl);
                    //清除之前的url，避免回退时一直要登录
                    break;
                case CODE_REQUEST_LOGIN:
                    needClearHistory=true;
                    if(!TextUtils.isEmpty(urlReLoadAfterLogin)){
                        String activeUrl;
                        if(urlReLoadAfterLogin.startsWith("http")){
                            activeUrl=urlReLoadAfterLogin+ApplicationHelper.getApplication().getUser().getID()+
                                "&isReceive=1";
                        }else{
                            activeUrl=URLUtil.CBB_WEB_URL+urlReLoadAfterLogin+ApplicationHelper.getApplication().getUser().getID()+
                                    "&isReceive=1";
                        }
                        mWebView.loadUrl(activeUrl);
                    }
                    break;
                case CODE_LOAN_RED_PACKET_LOGIN:
                    startLoanRedPacket();
                    break;
            }
        }
        if(webShare!=null){
            webShare.onActivityResult(requestCode,resultCode,data);
        }
    }
}
